package com.example.ssm.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
@RequestMapping("test")
public class TestController extends BaseController {

    @RequestMapping("sign_in")
    private String signIn() {
        int id = Integer.parseInt(request.getParameter("id"));
        String password=request.getParameter("password");
        String sql="select * from db_user.user where id=? and password =?";
        Connection connection=null;
        connection=DB.getConnection();
        ResultSet resultSet=null;
        PreparedStatement preparedStatement=null;
        try {
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setInt(1,id);
            preparedStatement.setString(2,password);
            resultSet=preparedStatement.executeQuery();
            resultSet.next();
            if(resultSet!=null){
                session.setAttribute("message"," sign in is success");

                return "redirect:/index.jsp";
            }
            session.setAttribute("message"," sign in is error");
            return "redirect:/index.jsp";
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }
    @RequestMapping("sign_up")
    private String  signUp(){
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String sql="insert into db_user.user (username,password)values(?,?)";
        Connection connection=null;
        connection=DB.getConnection();
        ResultSet resultSet=null;
        PreparedStatement preparedStatement=null;
        try {
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            preparedStatement.executeUpdate();

            preparedStatement = connection.prepareStatement("select last_insert_id()");
            resultSet = preparedStatement.executeQuery();
            resultSet.next();
            int id = resultSet.getInt(1);

            request.getSession().setAttribute("Info","you id is "+ id);
            return "redirect:/index.jsp";

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        }


    }
